﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SocketTest
{
    public class ClientInfo
    {
        public TaskCompletionSource<byte[]> TaskCompletionSource { get; set; } = new TaskCompletionSource<byte[]>(TaskCreationOptions.None);
        public int Index { get; internal set; }
        public byte[] Buffer { get; set; }
    }

    internal class TestServer
    {
        private List<ClientInfo> clients;
        private byte[] buffer;
        public void Test()
        {
            _ = Task.Run(this.CameraImageMethod);

            this.clients = new List<ClientInfo>();
            for (int i = 0; i < 5; i++)
            {
                var info = new ClientInfo()
                {
                    Index = i
                };
                this.clients.Add(info);

                _ = Task.Factory.StartNew(this.ClientMethod, info);
            }

        }

        private async Task ClientMethod(object state)
        {
            var info = state as ClientInfo;

            while (true)
            {
                var time = DateTime.Now;
                if (info.Buffer == null)
                    continue;
                var buffer = info.Buffer;
                var el = DateTime.Now - time;
                Trace.WriteLine($"[{DateTime.Now:HH.MM:ss.fff}][{info.Index}] 已获取到图片信息 -> [{el.TotalMilliseconds}] ms");
                info.Buffer = null;
            }

        }

        private void CameraImageMethod()
        {
            var map = new Bitmap(@"C:\Users\raozh\Pictures\Saved Pictures\微信图片_20240701224336.jpg");
            var ms = new MemoryStream();
            map.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            var buffer = ms.GetBuffer();

            while (true)
            {
                this.buffer = buffer;
                Thread.Sleep(50);
            }
        }
    }
}
